<template>
  <div class="app-container">
    <!-- 查询 -->
    <tl-list-search ref="search" style="margin:6px 0" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" v-if="isHeaderDisplay">
      <template slot="search">
        <el-form-item class="qryItem" label="申请人" style="margin-left:-14px">
          <el-input v-model="queryParam.qry_user" placeholder="工号或姓名"></el-input>
        </el-form-item>
        <el-form-item class="qryItem" label="单据日期" prop="qry_begindocdate">
          <el-date-picker v-model="queryParam.qry_begindocdate" type="date" style="width:150px" value-format="yyyy-MM-dd" placeholder="开始时间" />&nbsp;至
          <el-date-picker v-model="queryParam.qry_enddocdate" type="date" style="width:150px" value-format="yyyy-MM-dd" placeholder="结束时间" />
        </el-form-item>
        <el-form-item class="qryItem" label="单据状态">
          <el-select v-model="queryParam.qry_state" clearable>
            <el-option v-for="item in codeModel.stateList" :key="item.code" :label="item.name" :value="item.code" clearable />
          </el-select>
        </el-form-item>
      </template>
    </tl-list-search>
    <!-- 工具栏 -->
    <tl-list-toolbar class="tl-list-toolbar" ref="toolbar" :refMainTable="$refs.mainTable" currentModuleTableCode="mpmProjectRisk/main" :startColumn="3" @add="openAddDialog('editForm')" @exportExcel="doExportExcel" @deleteBatch="doDeleteBatch" @refresh="doRefresh" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :isDisplayDeleteBatch="false">
      <template slot="left-btn"> </template>
    </tl-list-toolbar>
    <div>
      <!-- 列表选择 -->
      <div class="table-alert-div" ref="selector">
        <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
          <template slot="title">
            已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRowKeys.length }}</a
            >项&nbsp;&nbsp;
            <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
          </template>
        </el-alert>
      </div>
      <!--表格渲染-->
      <el-table class="tl-table" ref="mainTable" :height="tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName" :cell-class-name="doChangeCellClassName">
        <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
        <el-table-column prop="riskcode" label="风险编号" width="130px" sortable="custom" sort-by="riskcode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="待处理" width="80px" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-tag v-if="isInApprovalList(scope.row)" type="success">是</el-tag>
            <template v-else
              >否</template
            >
          </template>
        </el-table-column>
        <el-table-column prop="dispstate" label="审批状态" width="100px" sortable="custom" sort-by="state" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-tag :type="changeStateType(scope.row.state)">
              {{ scope.row.dispstate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="latestphase" label="最新阶段" width="100px" sortable="custom" sort-by="latestphase" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column prop="dispriskstatus" label="风险状态" width="85px" sortable="custom" sort-by="riskstatus" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispriskproperty" label="风险性质" width="85px" sortable="custom" sort-by="riskproperty" align="center" header-align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.dispriskproperty === '机会'" type="success">机会</el-tag>
            <el-tag v-else type="danger">威胁</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="disprisklevel" label="风险等级" width="85px" class="risk-level-col" sortable="custom" sort-by="risklevel" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column prop="riskdescription" label="风险描述" min-width="235px" sortable="custom" sort-by="riskdescription" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="riskmeasure" label="风险措施" min-width="250px" sortable="custom" sort-by="riskmeasure" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="influencequantization" label="风险影响评估" min-width="250px" sortable="custom" sort-by="influencequantization" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispriskprobability" label="风险可能性" width="150px" sortable="custom" sort-by="riskprobability" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispriskinfluencelevel" label="风险影响程度" width="150px" sortable="custom" sort-by="riskinfluencelevel" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="riskdate" label="风险登记日期" width="110px" sortable="custom" sort-by="riskdate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="responsible" label="风险责任人" width="95px" sortable="custom" sort-by="responsible" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="responsiblecode" label="风险责任人工号" width="120px" sortable="custom" sort-by="responsiblecode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="riskmeasuredue" label="风险措施计划完成日期" width="170px" sortable="custom" sort-by="riskmeasuredue" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="disprisktrend" label="风险趋势" width="85px" sortable="custom" sort-by="risktrend" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="feedback" label="反馈响应" min-width="250px" sortable="custom" sort-by="feedback" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column prop="docno" label="单据编号" width="120px" sortable="custom" sort-by="docno" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="docdate" label="单据日期" width="100px" sortable="custom" sort-by="docdate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="username" label="申请人姓名" width="120px" sortable="custom" sort-by="username" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="deptname" label="申请部门" width="155px" sortable="custom" sort-by="deptname" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="submitdate" label="提交日期" width="100px" sortable="custom" sort-by="submitdate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="description" label="备注" width="100px" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column label="操作" width="95px" v-slot="scope" fixed="right">
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-view" @click.native="openViewDialog('editForm', scope.row.id)">查看</el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit" @click.native="openEditDialog('editForm', scope.row.id)" :disabled="(scope.row.state !== 0 && scope.row.state !== 2) || user.code !== scope.row.usercode">编辑</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" :disabled="(scope.row.state !== 0 && scope.row.state !== 2) || user.code !== scope.row.usercode" @click.native="doDelete(scope.row.id)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </el-table>
      <!-- 列表分页 -->
      <el-row class="pagebar" ref="pager">
        <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
      </el-row>
      <tl-edit ref="editForm" @refresh="doRefresh" :projectinfo="this.projectinfo"></tl-edit>
      <tl-approval ref="approvalForm" :projectinfo="this.projectinfo" @refresh="doRefresh"></tl-approval>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import tlEdit from './edit'
import tlApproval from '@/views/cbo/cboApprovalNodeIns/approvalOne'
/** 常量 **/
import topscommConst from '@tapui/const/tapConst'
/** 工具类 */
import { Loading } from 'element-ui'

import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
export default {
  name: 'mpmProjectRisk',
  mixins: [mixin_list],
  components: { tlEdit, tlApproval },
  props: {
    projectinfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      description: '项目风险-列表查询',
      urlPrefix: '/mpm/projectRisk/',
      url: {
        queryCodeList: '/mpm/projectRisk/dataCodeList',
        // 待办审批list url
        queryApprovalList: '/cbo/approvalNodeIns/queryApprovalList',
        ifReviewed: '/mpm/projectReview/ifReviewed'
      },
      reduceHeight: 264,
      // 根据风险等级 降序排序
      sorterInfo: {
        sidx: 'risklevel',
        sord: 'desc'
      },
      approvalDataList: [],
      sourcetype: 'MpmProjectRisk'
    }
  },
  methods: {
    /** 打开新增对话框实现，添加复盘校验 */
    openAddDialog(editForm, rowData) {
      getAction(this.url.ifReviewed, { projectcode: this.projectinfo.projectcode }).then((res) => {
        if (res.success) {
          if (res.result) {
            this.$tap.alert('该项目已提交复盘审批，无法新增单据!')
          } else {
            if (!this.beforeOpenAddDialog(editForm, rowData)) {
              return
            }
            this.$refs[editForm].isAdd = true
            this.$refs[editForm].visible = true
            this.$refs[editForm].disableEditSubmit = false
            this.$nextTick(() => {
              this.afterOpenAddDialog(editForm, rowData)
            })
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
      .catch((err) => {
          this.$tap.alert(err, 'warninig')
      })
    },
    // 审批结束后刷新列表和顶部tab
    doRefresh() {
      this.loadData({})
      this.$emit('refreshIndex')
    },
    // 禁用表格前面的选择
    doDisableCheckBox(row, index) {
      if (row.state === 0 && row.state === 2) {
        return false
      } else {
        return true
      }
    },

    // 风险等级列样式匹配
    doChangeCellClassName({ row, column }) {
      if (column.property === 'disprisklevel') {
        switch (row.risklevel) {
          case '0':
            return 'low-level'
          case '1':
            return 'middle-level'
          case '2':
            return 'high-level'
        }
      }
    },
    beforeLoadData() {
      // 用户只能查看当前项目下的数据
      this.queryParam.qry_projectid = this.$attrs.projectId
      // 获取用户待办审批列表
      this.getApprovalDataList()
      return true
    },
    // 获取用户当前待审批列表 =>approvalDataList
    getApprovalDataList() {
      // 参数 在com.topscomm.mpm.cboController.CboApprovalNodeInsController#queryApprovalList 里面写死了必须page
      let approvalParam = {
        qry_sourcetype: this.sourcetype,
        qry_approvaluserid: this.user.id,
        sidx: 'nodeins.createon',
        currentPage: '1',
        pageSize: '1000'
      }

      getAction(this.url.queryApprovalList, approvalParam)
        .then((res) => {
          if (res.success) {
            this.approvalDataList = res.result.dataList
          }
        })
        .catch((err) => {
          this.$tap.alert(err, 'warninig')
        })
    },
    isInApprovalList(row) {
      return this.approvalDataList.filter((item) => item.sourceid === row.id).length > 0
    },
    // 双击 判断审核或查看
    doRowDbClick(row, column, event) {
      // 状态1为审批中
      if (row.state === 1) {
        this.openApproval(row.id)
      } else if (row.state === 0) {
        this.openEditDialog('editForm', row.id)
      } else {
        this.openViewDialog('editForm', row.id)
      }
    }, // 传入ApprovalNodeIns 的 主键id 打开对应审批界面
    openApprovalDialog(id) {
      this.$refs.approvalForm.nodeInsId = id
      this.$refs.approvalForm.visible = true
    }, // 传入当前问题的id 获取用户待办审批并找到对应nodeins 打开审批界面
    openApproval(problemid) {
      // 简单定时加载动画
      let loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
      })
      // 根据id即审批中的sourceid在待审批中找到唯一对应的ApprovalNodeIns
      let problemNodeIns = this.approvalDataList.filter(function(nodeIns) {
        return nodeIns.sourceid === problemid
      })

      // let id = problemNodeIns[0].id 若 problemNodeIns 为空 则置为null
      let id = (function(problemNodeIns) {
        if (problemNodeIns.length !== 0) {
          return problemNodeIns[0].id
        } else {
          return null
        }
      })(problemNodeIns)
      // 待办中无此问题则查看
      if (id === null) {
        this.openViewDialog('editForm', problemid)
        loadingInstance.close()
      } else {
        /* 打开审批界面*/
        this.openApprovalDialog(id)
        loadingInstance.close()
      }
    },
    /** 改变审核状态标签颜色 */
    changeStateType(state) {
      return state === 0 ? 'info' : state === 2 ? 'danger' : state === 9 ? 'success' : ''
    }
  }
}
</script>

<style lang="scss" scoped>
$riskLevels: high, middle, low;
$riskColors: #ff6363, #ffe119, #bfef45;
//for 循环 根据风险低中高 匹配颜色和字体样式
@for $i from 1 through 3 {
  .el-table /deep/ .#{nth($riskLevels,$i)}-level {
    background-color: nth($riskColors, $i);
    //背景红色 则加粗
    @if $i == 1 {
      font-weight: bold;
    }
    color: #303133 !important;
  }
}
.el-drawer__body {
  overflow: unset;
}
.app-container {
  margin: 0;
}
</style>
